package com.rovinj_server.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.rovinj_server.R;
import com.rovinj_server.adapter.InventorysScanningAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventoryTaskSub;
import com.rovinj_server.entity.SubmitTask;
import com.rovinj_server.receiver.KeyReceiverListener;
import com.rovinj_server.utisl.Util;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pda.serialport.Barcode1DManager;

/**
 * 获取盘底数据
 * 扫描条码
 * 验证条码
 * 非次货位条目 报警提示
 * 提交保存
 * 提交2次做对比
 * 完成盘点单 发数据服务端
 * <p>
 * 扫描按钮： 扫描条码 正常 更新数据  盘点 条码数量
 * 重扫按钮： 删除 数据库 盘点数据设置为0
 */

public class TaskSaninngActivity extends AutoLayoutActivity implements KeyReceiverListener {
    public static final String TAG = "---InventorysActivity";
    public List<InventoryTaskSub> mDataList = new ArrayList<>();
    @Bind(R.id.recycler_view_m)
    RecyclerView mRecyclerViewM;
    @Bind(R.id.butt_scanning)
    Button mButtScanning;
    @Bind(R.id.fah_but_again)
    Button mFahButAgain;
    @Bind(R.id.but_complete)
    Button mButComplete;
    @Bind(R.id.diff_qty)
    TextView mDiffQty;
    @Bind(R.id.sao_qty)
    TextView mSaoQty;
    @Bind(R.id.sj_qty)
    TextView mSjQty;
    public int tymeSao = 0;
    @Bind(R.id.disc_number)
    TextView mDiscNumber;
    private InventorysScanningAdapter mAdapter;
    private Timer scanTimer = null;
    private Barcode1DManager manager;
    private InventoryTaskSub mTaskSub;
    private DBManager mDbManager;
    private String mLocation;
    private String mId;
    private List<InventoryTaskSub> mTaskSubListData;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == Barcode1DManager.Barcode1D) {
                String str = msg.getData().getString("data").toString();
                String data = str.replace("\r\n", "");
                Log.d(TAG, "--条码--" +data +"-----"+ data.length() );
                Util.play(1, 0);
                yzBarode(data);
            }
            switch (msg.what) {
                case 0:
                    mDbManager.updateQtyData(mId);
                    tymeSao++;
                    mSaoQty.setText(tymeSao + "");
                    InventoryTaskSub idTaskSubLis = mDbManager.findIDTaskSubLis(mId); //扫描条目更新数据库数量
                    int discNumber1 = idTaskSubLis.getDiscNumber();
                    mDiscNumber.setText(discNumber1+"");
                  //  mAdapter.setList(mDataList);
                    mAdapter.notifyDataSetChanged();
                    break;

                case -1:
                    Toast.makeText(TaskSaninngActivity.this, "非法标签", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        ;
    };

    /**
     * 验证条码
     */
    private void yzBarode(String data) {
        Message message = new Message();
        if (data != null && data.length() > 0) {
                if(data.length()==18){

                    String barode = mTaskSub.getBarode();
                    for (int i = 0; i < mTaskSubListData.size(); i++) {
                        String barode1 = mTaskSubListData.get(i).getBarode();
                    }
                    message.what = 0;
                    mHandler.sendMessage(message);
                }else {
                    message.what = -1;
                    mHandler.sendMessage(message);
                }
          /*  InventoryTaskSub inventoryTaskSub = new InventoryTaskSub();
            inventoryTaskSub.setBarode(data);
            inventoryTaskSub.setLocation(mLocation);
            mDataList.add(inventoryTaskSub);*/

        }

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventorys_scanning);
        ButterKnife.bind(this);
        manager = new Barcode1DManager();
        manager.Open(mHandler);
        mDbManager = new DBManager(this);
        mDbManager.copyDBFile();
        Util.initSoundPool(this);
        hidStater();
        initData();
        initView();

    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerViewM.setLayoutManager(linearLayoutManager);
        //mAdapter = new InventorysScanningAdapter(mDataList);
        mRecyclerViewM.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mId = (String) intent.getSerializableExtra("id");
            int  mIntID = (int) intent.getSerializableExtra("mIntID");
            mTaskSub = mDbManager.findIDTaskSubLis(mId);
            mTaskSubListData = mDbManager.findTaskSubListData(mIntID);
            if (mTaskSub != null) {
                mDataList.add(mTaskSub);
                mSjQty.setText(mTaskSub.getSjnumber());
                mDiffQty.setText(mTaskSub.getDiffNumber());
                mLocation = mTaskSub.getLocation();
                int discNumber = mTaskSub.getDiscNumber();
                mId = mTaskSub.getId();
                mDiscNumber.setText(discNumber+"");
            }
        }
    }

    @OnClick({R.id.fh, R.id.butt_scanning, R.id.fah_but_again, R.id.but_complete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.butt_scanning: //扫描
                getBarcode();
                break;
            case R.id.fah_but_again: //完成 //修改状态
                if (mId != null && mId.length() > 0) {
                    mDbManager.updateData(mId, "完成");
                    Toast.makeText(this, "完成提交成功", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.but_complete: //更新数量 重扫
                Toast.makeText(this, "删除数量", Toast.LENGTH_SHORT).show();
                mDbManager.updateQtyNullData(mId);
                mDiscNumber.setText("0");
                break;
            case R.id.fh:
                finish();
                break;
        }
    }


    //  扫描条目按获取
    private void getBarcode() {
        if (mButtScanning.getText().toString().equals("扫描")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    manager.Scan();
                }
            }).start();
        }
    }

    /**
     * 隐藏状态栏
     */
    private void hidStater() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
    }

    @Override
    protected void onDestroy() {
        if (scanTimer != null) {
            scanTimer.cancel();
        }
        manager.Close();
        super.onDestroy();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int keyCode = intent.getIntExtra("keyCode", 0);
        Log.d(TAG, "按了按键，keycode是=" + intent.getIntExtra("keyCode", 0));
        switch (keyCode) {
            case 133:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mButtScanning.isEnabled()) {
                            mButtScanning.performClick();
                        }
                    }
                });
                break;
        }
    }
}
